package main.utils;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class StrUtil {
	
	public String cleanStr(String str){
		str=str.replaceAll("&","&amp;");
		str=str.replaceAll("<","&lt;");
	    str=str.replaceAll(">","&gt;");
	    str=str.replaceAll("'","");
	    str=str.replaceAll(";","");
	    str=str.replaceAll("--","");
	    str=str.replaceAll("/","");
	    str=str.replaceAll("%","");
		return str;
	}
	
	public String toGBK(String strvalue) {
		try {
			if (strvalue == null) {			//当变量strvalue为null时
				return "";					//返回空的字符串
			} else {
				strvalue = new String(strvalue.getBytes("ISO-8859-1"), "GBK");//将字符串转换为GBK编码
				return strvalue;			//返回转换后的输入变量strvalue
			}
		} catch (Exception e) {
			return "";
		}
	}

	public String toUTF8(String strvalue) {
		try {
			if (strvalue == null) {			//当变量strvalue为null时
				return "";					//返回空的字符串
			} else {
				strvalue = new String(strvalue.getBytes("ISO-8859-1"), "UTF-8");//将字符串转换为UTF8编码
				return strvalue;		//返回转换后的输入变量strvalue
			}
		} catch (Exception e) {
			return "";
		}
	}
	
	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String key, String value){
		Cookie[]cookies = request.getCookies();
		Boolean isExist = false;
		for(Cookie cookie : cookies){
			if (key.equals(cookie.getName())) {
				cookie.setValue(value);
				isExist = true;
			}
		}
		if (!isExist) {
			Cookie cookie = new Cookie(key, value);
			response.addCookie(cookie);
		}
	}
	
	public static Boolean valiInput(String string){
		Pattern pattern = Pattern.compile("[a-zA-Z_0-9]{6,30}");
		Matcher matcher = pattern.matcher(string);
		Boolean isMatch = matcher.matches();
		return isMatch;
	}
	
	public static String getRandomFileName() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().toUpperCase();
	}
	
}
